
package com.android.fitnesscenter.version;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.TextUtils;

import com.android.fitnesscenter.R;
import com.android.fitnesscenter.utils.ConfigProperties;
import com.android.fitnesscenter.utils.ConfigProperties.RoleInfo;
import com.android.fitnesscenter.utils.Loger;
import com.android.fitnesscenter.utils.PhoneStateUtil;
import com.android.fitnesscenter.utils.ToastHelper;
import com.android.fitnesscenter.utils.Version;
import com.android.fitnesscenter.utils.ViewHelper;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

public class UpgradeProgress {
    private ViewHelper mViewHelper;
    private String upgradeApkUrl;
    private String newVersionLog;
    private boolean hasNewVersion = false;
    private boolean forceUpdate = false;
    private boolean isAuto;
    private boolean isMain = false;
    private Activity contextActivity;
    private static UpgradeProgress instance;
    private MyBroadcastReceiver broadcastReceiver;

    /**
     * @return UpgradeProgress 单例
     */
    public static synchronized UpgradeProgress getInstance() {
        if (instance == null) {
            synchronized (UpgradeProgress.class) {
                if (instance == null) {
                    instance = new UpgradeProgress();
                }
            }
        }
        return instance;
    }

    // 适用于不同activity中检测更新
    public synchronized void checkVersion(Activity activity, Boolean isAuto, boolean isMain) {
        this.isAuto = isAuto;
        this.isMain = isMain;
        boolean hasSDCard = android.os.Environment.MEDIA_MOUNTED
                .equals(android.os.Environment.getExternalStorageState());
        this.contextActivity = activity;
        mViewHelper = new ViewHelper(contextActivity);
        if (!PhoneStateUtil.hasInternet() || !hasSDCard) {
            if (!hasSDCard) {
                mViewHelper.showBTNDialog(contextActivity.getResources()
                        .getString(R.string.text_check_net_sdcard));
            }
            if (!PhoneStateUtil.hasInternet()) {
                mViewHelper.showBTNDialog("请检查手机网络");
            }
            return;
        }

        if (broadcastReceiver != null) {
            ToastHelper.getInstance().showLongMsg("已在处理更新中");
            return;
        }
        initBroadcast();
        requestNewVersion();
    };

    private ProgressDialog mDialog;

    private void requestNewVersion() {
        RequestParams params = new RequestParams();
        HttpUtils http = new HttpUtils();
        String versionStr = "";
        switch (ConfigProperties.APP_TYPE) {
            case RoleInfo.CLIENT:
                versionStr = "queryNewVersion.do";
                break;
            case RoleInfo.SERVER:
                versionStr = "queryAdminVersion.do";
                break;
        }
        String url = ConfigProperties.SERVICE_URL + versionStr;
        Loger.e("request new version");
        http.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {
            @Override
            public void onStart() {
                if (!isMain && contextActivity != null && !contextActivity.isFinishing()) {
                    try {
                        if (mDialog == null) {
                            mDialog = new ProgressDialog(contextActivity);
                        }
                        mDialog.setMessage("加载中,请等待...");
                        mDialog.setCanceledOnTouchOutside(false);
                        mDialog.show();
                    } catch (Exception e) {

                    }
                }
            }

            @Override
            public void onSuccess(ResponseInfo<String> stringResponseInfo) {
                Loger.e("stringResponseInfo is " + stringResponseInfo.result);
                if (contextActivity == null || contextActivity.isFinishing()) {
                    Loger.e("Main activity is finish!");
                    return;
                }
                try {
                    if (mDialog != null) {
                        mDialog.dismiss();
                    }
                } catch (Exception e) {

                }
                if (stringResponseInfo != null && !TextUtils.isEmpty(stringResponseInfo.result)) {
                    try {
                        JSONObject jsonObject = new JSONObject(stringResponseInfo.result);
                        if (jsonObject != null) {
                            boolean success = jsonObject.getBoolean("success");
                            if (success) {
                                JSONObject jsonObject2 = jsonObject.getJSONObject("model");
                                int verCode = jsonObject2.getInt("verCode");
                                int versionCode = Version.getVersionCode();
                                Loger.e("verCode is " + verCode + " --- versionCoe is " + versionCode);
                                if (verCode > versionCode) {
                                    upgradeApkUrl = jsonObject2.getString("verPath");
                                    hasNewVersion = true;
                                    String verName = jsonObject2.getString("verName");
                                    newVersionLog = "版本号：" + verName + "\n" + "更新内容：\n"
                                            + jsonObject2.getString("detail") + "\n";
                                } else {
                                    hasNewVersion = false;
                                }
                            }
                        }
                    } catch (JSONException e) {
                        Loger.e("JSONException e is " + e);
                    }
                    Loger.e("hasNewVersion is " + hasNewVersion + " url is " + upgradeApkUrl + " -- log ---"
                            + newVersionLog);
                    checkCurrentStatus();
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                mViewHelper.showErrorDialog(error);
                contextActivity.getApplicationContext().unregisterReceiver(
                        broadcastReceiver);
                broadcastReceiver = null;
            }
        });
    }

    private void checkCurrentStatus() {
        // 已经是最新版本,且是手动点击更新的
        if (!hasNewVersion && !this.isAuto) {
            mViewHelper.showBTNDialog(contextActivity.getString(R.string.txt_upgrade_new_version));
            contextActivity.getApplicationContext().unregisterReceiver(
                    broadcastReceiver);
            broadcastReceiver = null;
        }
        // 已经是最新版本,自动更新的，不显示最高版本
        if (!hasNewVersion && this.isAuto) {
            contextActivity.getApplicationContext().unregisterReceiver(
                    broadcastReceiver);
            broadcastReceiver = null;
        }
        // 有新版本，给出提示
        if (hasNewVersion) {
            if (forceUpdate) {
                forceUpdate();
            } else {
                noticeUpdate();
            }

        }
    }

    private void noticeUpdate() {
        // 确认开始更新按钮
        OnClickListener positiveListener = new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent updateIntent = new Intent(contextActivity,
                        UpgradeVersionService.class);
                updateIntent.putExtra("titleId", R.string.app_name);
                updateIntent.putExtra("upgradeApkUrl", upgradeApkUrl);
                Loger.d("======upgradeApkUrl======" + upgradeApkUrl);
                contextActivity.startService(updateIntent);
            }

        };
        OnClickListener negativeListener = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 本次不再提醒更新
                // TODO StoreSession.setSuggestUpdate(false);
                if (broadcastReceiver != null) {
                    contextActivity.getApplicationContext()
                            .unregisterReceiver(broadcastReceiver);
                }
                broadcastReceiver = null;
            }

        };
        OnCancelListener cancleListener = new OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                if (broadcastReceiver != null) {
                    contextActivity.getApplicationContext()
                            .unregisterReceiver(broadcastReceiver);
                }
                broadcastReceiver = null;
            }
        };
        try {
            mViewHelper.showBTN2Dialog(contextActivity
                    .getString(R.string.upgrade_notification_title),
                    newVersionLog, contextActivity
                            .getString(R.string.upgrade_btn_upgrade),
                    contextActivity
                            .getString(R.string.upgrade_btn_nexttime),
                    positiveListener, negativeListener, cancleListener);
        } catch (Exception e) {
            Loger.e(e.getMessage());
        }

    }

    private void forceUpdate() {
        // 确认开始更新按钮
        OnClickListener positiveListener = new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent updateIntent = new Intent(contextActivity, UpgradeVersionService.class);
                updateIntent.putExtra("titleId", R.string.app_name);
                updateIntent.putExtra("upgradeApkUrl", upgradeApkUrl);
                Loger.d("======upgradeApkUrl======" + upgradeApkUrl);
                contextActivity.startService(updateIntent);
            }

        };
        OnClickListener negativeListener = new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (broadcastReceiver != null) {
                    contextActivity.getApplicationContext().unregisterReceiver(broadcastReceiver);
                }
                broadcastReceiver = null;
                contextActivity.finish();
            }

        };
        OnCancelListener cancleListener = new OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                if (broadcastReceiver != null) {
                    contextActivity.getApplicationContext().unregisterReceiver(broadcastReceiver);
                }
                broadcastReceiver = null;
                contextActivity.finish();
            }
        };
        try {
            mViewHelper.showBTN2Dialog(contextActivity.getString(R.string.upgrade_notification_title),
                    newVersionLog, contextActivity.getString(R.string.upgrade_btn_upgrade),
                    "退出程序", positiveListener, negativeListener, cancleListener);
        } catch (Exception e) {
            Loger.e(e.getMessage());
        }

    }

    private class MyBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(UpgradeVersionService.BROADCAST_ACTION)) {
                Intent updateIntent = new Intent(contextActivity, UpgradeVersionService.class);
                updateIntent.putExtra("titleId", R.string.app_name);
                updateIntent.putExtra("upgradeApkUrl", upgradeApkUrl);
                Loger.d("======upgradeApkUrl======" + upgradeApkUrl);
                contextActivity.stopService(updateIntent);
                if (intent.getBooleanExtra("downloadDone", false)) {
                    ToastHelper.getInstance().showLongMsg(contextActivity.getString(R.string.upgrade_success));
                    contextActivity.getApplicationContext().unregisterReceiver(broadcastReceiver);
                    broadcastReceiver = null;
                } else {
                    ToastHelper.getInstance().showLongMsg(contextActivity.getString(R.string.upgrade_fail_down));
                    contextActivity.getApplicationContext().unregisterReceiver(broadcastReceiver);
                    broadcastReceiver = null;

                }

            }
        }

    }

    private void initBroadcast() {
        // 生成广播处理
        if (broadcastReceiver != null) {
            contextActivity.getApplicationContext().unregisterReceiver(broadcastReceiver);
        }
        broadcastReceiver = new MyBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter(UpgradeVersionService.BROADCAST_ACTION);
        contextActivity.getApplicationContext().registerReceiver(broadcastReceiver, intentFilter);
    }
}
